/*
 * This program is free software: you can redistribute it and/or modify it under
 * the terms of the GNU General Public License as published by the Free Software
 * Foundation, either version 3 of the License, or (at your option) any later
 * version.
 * 
 * This program is distributed in the hope that it will be useful, but WITHOUT
 * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
 * FOR A PARTICULAR PURPOSE. See the GNU General Public License for more
 * details.
 * 
 * You should have received a copy of the GNU General Public License along with
 * this program. If not, see <http://www.gnu.org/licenses/>.
 */
package net.sf.l2j.gameserver.network.clientpackets;

import net.sf.l2j.Config;
import net.sf.l2j.gameserver.datatables.SkillTable;
import net.sf.l2j.gameserver.datatables.SkillTreeTable;
import net.sf.l2j.gameserver.datatables.SpellbookTable;
import net.sf.l2j.gameserver.model.L2PledgeSkillLearn;
import net.sf.l2j.gameserver.model.L2ShortCut;
import net.sf.l2j.gameserver.model.L2Skill;
import net.sf.l2j.gameserver.model.L2SkillLearn;
import net.sf.l2j.gameserver.model.actor.L2Npc;
import net.sf.l2j.gameserver.model.actor.instance.L2FishermanInstance;
import net.sf.l2j.gameserver.model.actor.instance.L2NpcInstance;
import net.sf.l2j.gameserver.model.actor.instance.L2PcInstance;
import net.sf.l2j.gameserver.model.actor.instance.L2VillageMasterInstance;
import net.sf.l2j.gameserver.network.SystemMessageId;
import net.sf.l2j.gameserver.network.serverpackets.ExStorageMaxCount;
import net.sf.l2j.gameserver.network.serverpackets.PledgeSkillList;
import net.sf.l2j.gameserver.network.serverpackets.ShortCutRegister;
import net.sf.l2j.gameserver.network.serverpackets.StatusUpdate;
import net.sf.l2j.gameserver.network.serverpackets.SystemMessage;
import net.sf.l2j.gameserver.util.IllegalPlayerAction;
import net.sf.l2j.gameserver.util.Util;

public class RequestAcquireSkill extends L2GameClientPacket
{
	private int _id;
	private int _level;
	private int _skillType;
	
	@Override
	protected void readImpl()
	{
		_id = readD();
		_level = readD();
		_skillType = readD();
	}
	
	@Override
	protected void runImpl()
	{
		final L2PcInstance player = getClient().getActiveChar();
		if (player == null)
			return;
		
		if (_level < 1 || _level > 1000 || _id < 1 || _id > 32000)
		{
			Util.handleIllegalPlayerAction(player, "Received wrong data for RequestAcquireSkill", Config.DEFAULT_PUNISH);
			_log.warning("Received wrong data for RequestAcquireSkill - id: " + _id + " level: " + _level + " for " + player.getName());
			return;
		}
		
		final L2Npc trainer = player.getCurrentFolkNPC();
		if ((trainer == null || !player.isInsideRadius(trainer, L2Npc.INTERACTION_DISTANCE, false, false)) && !player.isGM())
			return;
		
		player.setSkillLearningClassId(player.getClassId());
		
		/**
		 * If current skill lvl + 1 is not equal to the skill lvl you wanna learn (eg: You have Aggression lvl 3 and the packet sends info that you want to learn Aggression lvl 5, thus skipping lvl 4.) or the packet sends the same level or lower (eg: Aggression lvl 3 and the packet sends info that
		 * you want to learn Aggression level 3).
		 */
		if (Math.max(player.getSkillLevel(_id), 0) + 1 != _level)
			return;
		
		final L2Skill skill = SkillTable.getInstance().getInfo(_id, _level);
		
		int counts = 0;
		int requiredSp = 10000000;
		
		switch (_skillType)
		{
			case 0:
			{
				// Normal skills
				L2SkillLearn[] skills = SkillTreeTable.getInstance().getAvailableSkills(player, player.getSkillLearningClassId());
				for (L2SkillLearn s : skills)
				{
					L2Skill sk = SkillTable.getInstance().getInfo(s.getId(), s.getLevel());
					if (sk == null || sk != skill)
						continue;
					
					counts++;
					requiredSp = SkillTreeTable.getInstance().getSkillCost(player, skill);
				}
				
				if (counts == 0)
				{
					Util.handleIllegalPlayerAction(player, player.getName() + " tried to learn skill that he can't learn.", IllegalPlayerAction.PUNISH_KICK);
					return;
				}
				
				if (player.getSp() >= requiredSp)
				{
					int spbId = -1;
					
					// Divine inspiration require book for each level
					if (Config.DIVINE_SP_BOOK_NEEDED && skill.getId() == L2Skill.SKILL_DIVINE_INSPIRATION)
						spbId = SpellbookTable.getInstance().getBookForSkill(skill, _level);
					else if (Config.SP_BOOK_NEEDED && skill.getLevel() == 1)
						spbId = SpellbookTable.getInstance().getBookForSkill(skill);
					
					// Spellbook required
					if (spbId > -1)
					{
						if (!player.destroyItemByItemId("Consume", spbId, 1, trainer, false))
						{
							// Haven't spellbook
							player.sendPacket(SystemMessageId.ITEM_MISSING_TO_LEARN_SKILL);
							showSkillList(trainer, player);
							return;
						}
						
						SystemMessage sm = SystemMessage.getSystemMessage(SystemMessageId.S1_DISAPPEARED);
						sm.addItemName(spbId);
						player.sendPacket(sm);
					}
				}
				else
				{
					player.sendPacket(SystemMessageId.NOT_ENOUGH_SP_TO_LEARN_SKILL);
					showSkillList(trainer, player);
					return;
				}
				break;
			}
			case 1:
			{
				int costId = 0;
				int costCount = 0;
				
				// Skill Learn bug Fix
				L2SkillLearn[] skillsc = SkillTreeTable.getInstance().getAvailableSkills(player);
				for (L2SkillLearn s : skillsc)
				{
					L2Skill sk = SkillTable.getInstance().getInfo(s.getId(), s.getLevel());
					if (sk == null || sk != skill)
						continue;
					
					counts++;
					costId = s.getIdCost();
					costCount = s.getCostCount();
					requiredSp = s.getSpCost();
				}
				
				if (counts == 0)
				{
					Util.handleIllegalPlayerAction(player, player.getName() + " tried to learn skill that he can't learn.", IllegalPlayerAction.PUNISH_KICK);
					return;
				}
				
				if (player.getSp() >= requiredSp)
				{
					if (!player.destroyItemByItemId("Consume", costId, costCount, trainer, false))
					{
						// Haven't spellbook
						player.sendPacket(SystemMessageId.ITEM_MISSING_TO_LEARN_SKILL);
						showSkillList(trainer, player);
						return;
					}
					
					SystemMessage sm = SystemMessage.getSystemMessage(SystemMessageId.S2_S1_DISAPPEARED);
					sm.addItemName(costId);
					sm.addItemNumber(costCount);
					player.sendPacket(sm);
				}
				else
				{
					player.sendPacket(SystemMessageId.NOT_ENOUGH_SP_TO_LEARN_SKILL);
					showSkillList(trainer, player);
					return;
				}
				break;
			}
			case 2:
			{
				int itemId = 0;
				int repCost = 100000000;
				
				// Skill Learn bug Fix
				L2PledgeSkillLearn[] skills = SkillTreeTable.getInstance().getAvailablePledgeSkills(player);
				for (L2PledgeSkillLearn s : skills)
				{
					L2Skill sk = SkillTable.getInstance().getInfo(s.getId(), s.getLevel());
					if (sk == null || sk != skill)
						continue;
					
					counts++;
					itemId = s.getItemId();
					repCost = s.getRepCost();
					break;
				}
				
				if (counts == 0)
				{
					Util.handleIllegalPlayerAction(player, player.getName() + " tried to learn skill that he can't learn.", IllegalPlayerAction.PUNISH_KICK);
					return;
				}
				
				if (player.getClan().getReputationScore() >= repCost)
				{
					if (Config.LIFE_CRYSTAL_NEEDED)
					{
						if (!player.destroyItemByItemId("Consume", itemId, 1, trainer, false))
						{
							// Haven't item
							player.sendPacket(SystemMessageId.ITEM_MISSING_TO_LEARN_SKILL);
							L2VillageMasterInstance.showPledgeSkillList(player);
							return;
						}
						
						SystemMessage sm = SystemMessage.getSystemMessage(SystemMessageId.S2_S1_DISAPPEARED);
						sm.addItemName(itemId);
						sm.addItemNumber(1);
						player.sendPacket(sm);
					}
				}
				else
				{
					player.sendPacket(SystemMessageId.ACQUIRE_SKILL_FAILED_BAD_CLAN_REP_SCORE);
					L2VillageMasterInstance.showPledgeSkillList(player);
					return;
				}
				
				// Useless to update reputation score / set message for non-costing skill (Clan Imperium).
				if (repCost != 0)
				{
					player.getClan().takeReputationScore(repCost, true);
					player.sendPacket(SystemMessage.getSystemMessage(SystemMessageId.S1_DEDUCTED_FROM_CLAN_REP).addNumber(repCost));
				}
				
				// Skill addition and message
				player.getClan().addNewSkill(skill);
				player.sendPacket(SystemMessage.getSystemMessage(SystemMessageId.CLAN_SKILL_S1_ADDED).addSkillName(_id));
				
				if (Config.DEBUG)
					_log.fine("Learned pledge skill " + _id + " for " + requiredSp + " SP.");
				
				player.getClan().broadcastToOnlineMembers(new PledgeSkillList(player.getClan()));
				
				for (L2PcInstance member : player.getClan().getOnlineMembers(0))
					member.sendSkillList();
				
				L2VillageMasterInstance.showPledgeSkillList(player);
				return;
			}
			default:
			{
				_log.warning("Received wrong data for RequestAcquireSkill - unk1:" + _skillType);
				return;
			}
		}
		
		if (Config.DEBUG)
			_log.fine("Learned skill " + _id + " for " + requiredSp + " SP.");
		
		if (_skillType != 2)
		{
			player.setSp(player.getSp() - requiredSp);
			
			StatusUpdate su = new StatusUpdate(player);
			su.addAttribute(StatusUpdate.SP, player.getSp());
			player.sendPacket(su);
			
			SystemMessage sm = SystemMessage.getSystemMessage(SystemMessageId.LEARNED_SKILL_S1);
			sm.addSkillName(skill);
			player.sendPacket(sm);
			
			player.addSkill(skill, true);
			player.sendSkillList();
			
			updateShortCuts(player);
			showSkillList(trainer, player);
		}
	}
	
	private void updateShortCuts(L2PcInstance player)
	{
		// update all the shortcuts to this skill
		if (_level > 1)
		{
			L2ShortCut[] allShortCuts = player.getAllShortCuts();
			
			for (L2ShortCut sc : allShortCuts)
			{
				if (sc.getId() == _id && sc.getType() == L2ShortCut.TYPE_SKILL)
				{
					L2ShortCut newsc = new L2ShortCut(sc.getSlot(), sc.getPage(), sc.getType(), sc.getId(), _level, 1);
					player.sendPacket(new ShortCutRegister(newsc));
					player.registerShortCut(newsc);
				}
			}
		}
	}
	
	private void showSkillList(L2Npc trainer, L2PcInstance player)
	{
		if (trainer instanceof L2FishermanInstance)
			L2FishermanInstance.showFishSkillList(player);
		else
			L2NpcInstance.showSkillList(player, trainer, player.getSkillLearningClassId());
		
		// if skill is expand sendpacket :)
		if (_id >= 1368 && _id <= 1372)
			player.sendPacket(new ExStorageMaxCount(player));
	}
}